package com.boot.interceptor;

import com.boot.utils.JwtUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor,{}",request.getRequestURI());
        String token = getTokenFromCookie(request);
        if (token == null || token.isEmpty()) {
            sendError(response, 401, "no Token");
            return false;
        }
        // 验证 Token 是否有效
        if (jwtUtil.isTokenExpired(token)) {
            sendError(response, 401, "Token expired");
            return false;
        }
        BaseContext.setCurrentId(jwtUtil.getUserId(token));
        //Token 有效，放行请求
        return true;
    }

    private void sendError(HttpServletResponse response, int code, String message) throws IOException, IOException {
        response.setContentType("application/json");
        response.setStatus(code);
        response.getWriter().write("{\"code\":" + code + ", \"message\":\"" + message + "\"}");
    }
    // 从 Cookie 中提取 Token
    private String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if ("token".equals(cookie.getName())) { // 根据实际 Cookie 名称调整
                return cookie.getValue();
            }
        }
        return null;
    }

}
